package initialize

import (
	"fmt"
	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"time"
)

func InitLogger() {
	var writeSyncer zapcore.WriteSyncer

	writeSyncer = getLogWriter()

	encoder := getEncoder()
	core := zapcore.NewCore(encoder, writeSyncer, zapcore.DebugLevel)
	logger := zap.New(core, zap.AddCaller())
	zap.ReplaceGlobals(logger)
}

func getEncoder() zapcore.Encoder {
	encoderConfig := zap.NewProductionEncoderConfig()
	// 格式化时间 可自定义
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	encoder := zapcore.NewJSONEncoder(encoderConfig)
	//encoder.AddString("path", c.Request.URL.String())
	return encoder
}

// 保存文件日志切割
func getLogWriter() zapcore.WriteSyncer {
	tm := time.Now()
	lumberJackLogger := &lumberjack.Logger{
		Filename:   fmt.Sprintf("./log/%s.log", tm.Format("20060102")), // 日志名称
		MaxSize:    1,                                                  // 文件内容大小, MB
		MaxBackups: 5,                                                  // 保留旧文件最大个数
		MaxAge:     7,                                                  // 保留旧文件最大天数
		Compress:   false,                                              // 文件是否压缩
	}

	return zapcore.AddSync(lumberJackLogger)
}
